package pbx.service;


import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import pbx.model.Sip;


@Stateless
public class SipService {
	
	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Sip getById(Integer id){	
		return em.find(Sip.class, id);
	}
    
    public Sip save(Sip sip) {
    	em.persist(sip); 
    	return sip;
    }
    
    public Sip update(Sip sip) {
    	return em.merge(sip); 
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Sip.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Sip> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Sip e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
    
   // ------------------------------------------------------------------------------
    
	public Sip getByCode(String code) {
		Sip result = null;
		Query query = em.createQuery("SELECT e FROM Sip e WHERE e.code=:code");
		query.setParameter("code", code);
		try {
			result = (Sip) query.getSingleResult(); 
        }
    	catch (Exception e) {
			//e.printStackTrace();
		}
        return result; 
    }

	@SuppressWarnings("unchecked")
	public List<Sip> listByOrganizationId(Integer organization_id) {
    	List<Sip> results = null;
		Query query = em.createQuery("SELECT e FROM Sip e WHERE e.organization_id=:organization_id");
		query.setParameter("organization_id", organization_id);
		try {
			results = query.getResultList(); 
        }
    	catch (Exception e) {
			e.printStackTrace();
		}
        return results; 
	}
	

    
}

